#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright (c) 61DUke.

# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Readme Document for more details.
# Create: 2020-12-27

import os
from PIL import Image

__all__ = ["crop_gif2images", "crop_part_image"]


def crop_gif2images(source_image_path: str,
                    output_folder: str
                    ):
    """
    Convert the GIF motion picture to each static picture

    :param source_image_path:
    :param output_folder:
    :return:

    Example:
    ---------
    >>> crop_gif2images(
    ...     source_image_path="imgs/test.gif",
    ...     output_folder="source_output"
    ... )

    """
    if not isinstance(source_image_path, str) or not source_image_path:
        raise ValueError("source_image_path param must be string!")
    if not isinstance(output_folder, str) or not output_folder:
        raise ValueError("output_path param must be string!")

    with Image.open(source_image_path) as image:
        image_file = source_image_path.split("/")[-1]
        image_name, _ = image_file.split(".")
        if not os.path.exists(output_folder):
            os.mkdir(output_folder)
        try:
            while True:
                # 保存当前帧图片
                current = image.tell()
                image.save(os.path.join(output_folder, image_name + f"_{current}.png"))
                # 获取下一帧图片
                image.seek(current + 1)
        except EOFError:
            pass

    return True


def crop_part_image(source_image_path: str,
                    output_path: str,
                    box=None
                    ):
    """
    crop part image

    :param source_image_path:
    :param output_path:
    :param box: tuple (BOX_LEFT, BOX_UP, BOX_RIGHT, BOX_DOWN)

        This image returns to a rectangular area for ROI clipping.
        The box is a 4-tuple that defines the left, top, right,
        and bottom pixel coordinates.

    :return:

    Example:
    ---------

    >>> crop_part_image(
    ...     source_image_path="imgs/IMG_2229.JPG",
    ...     output_path="source_output.png",
    ...     box=(300, 200, 700, 800)
    ... )
    """
    if not isinstance(source_image_path, str) or not source_image_path:
        raise ValueError("source_image_path param must be string!")
    if not isinstance(output_path, str) or not output_path:
        raise ValueError("output_path param must be string!")
    if box and not isinstance(output_path, tuple) and len(box) != 4:
        raise ValueError("output_path param must be 4-tuple!")

    source_image = Image.open(source_image_path)
    if not box:
        return source_image.save(output_path)
    if len(box) != 4:
        raise ValueError("box tuple length must be 4!")
    roi_image = source_image.crop(box)
    # Save the processed image
    return roi_image.save(output_path)
